<template>
  <div class="container">
    <div class="header">
      <div class="form-item">
        <span>班级名:</span>
        <el-input
          placeholder="请输入班级名"
          v-model="queryParams.className"
          @keyup.enter.native="queryClass"
          clearable
        />
      </div>
      <el-button
        type="primary"
        icon="el-icon-search"
        style="margin-right: 20px"
        @click.enter="queryClass"
      >
        查询
      </el-button>

      <div class="form-item">
        <span>院系:</span>
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择院系"
          clearable
          :disabled="!departments.length"
          @change="departmentChange(queryParams.deptId)"
        >
          <el-option
            v-for="dept in departments"
            :key="dept.id"
            :label="dept.deptName"
            :value="dept.id"
          />
        </el-select>
      </div>

      <div class="form-item">
        <span>专业:</span>
        <el-select
          v-model="queryParams.majorId"
          placeholder="请选择专业"
          :disabled="!majorList.length"
          clearable
          @change="majorChange()"
        >
          <el-option
            v-for="major in majorList"
            :key="major.id"
            :label="major.majorName"
            :value="major.id"
          />
        </el-select>
      </div>

      <div class="form-item">
        <span>年级:</span>
        <el-select
          v-model="queryParams.gradeId"
          placeholder="请选择年级"
          clearable
          :disabled="!majorList.length"
          @change="gradeChange"
        >
          <el-option
            v-for="grade in gradeList"
            :key="grade.id"
            :label="grade.gradeName"
            :value="grade.id"
          />
        </el-select>
      </div>

      <el-button type="primary" icon="el-icon-plus" @click="addClass">
        添加班级</el-button
      >
    </div>

    <div class="content">
      <el-table :data="classData" style="width: 100%" :border="true">
        <el-table-column type="index" label="序号" width="100" align="center">
        </el-table-column>
        <el-table-column
          label="院系"
          prop="deptName"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="专业"
          prop="majorName"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column label="年级" prop="gradeName" align="center">
        </el-table-column>
        <el-table-column label="班级名" prop="className" align="center">
        </el-table-column>
        <el-table-column
          label="学生人数"
          prop="studentNum"
          width="80"
          align="center"
        >
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="updateClass(row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteClass(row)"
            ></el-button>
            <el-button type="success" size="mini" @click="assignCourseBtn(row)"
              >分配课程</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="1"
        :page-sizes="[2, 5, 8, 10]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 添加表单 -->
    <el-dialog
      :title="addClassForm.classId == '' ? '添加班级' : '修改班级'"
      :visible.sync="addDialogFormVisible"
    >
      <el-form :model="addClassForm" ref="addClassForm" :rules="addFormRules">
        <el-form-item
          label="选择院系:"
          :label-width="formLabelWidth"
          prop="deptId"
        >
          <el-select
            v-model="addClassForm.deptId"
            placeholder="请选择院系"
            clearable
            :disabled="!departments.length || isEditMode"
            @change="addDepartmentChange(addClassForm.deptId)"
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.deptName"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="选择专业:"
          :label-width="formLabelWidth"
          prop="majorId"
        >
          <el-select
            v-model="addClassForm.majorId"
            placeholder="请选择专业"
            :disabled="!addMajorList.length || isEditMode"
            clearable
            @change="addMajorChange()"
          >
            <el-option
              v-for="major in addMajorList"
              :key="major.id"
              :label="major.majorName"
              :value="major.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="选择年级:"
          :label-width="formLabelWidth"
          prop="gradeId"
        >
          <el-select
            v-model="addClassForm.gradeId"
            placeholder="请选择年级"
            clearable
            :disabled="!addGradeList.length || isEditMode"
          >
            <el-option
              v-for="grade in addGradeList"
              :key="grade.id"
              :label="grade.gradeName"
              :value="grade.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="班级名:"
          :label-width="formLabelWidth"
          prop="className"
        >
          <el-input
            v-model="addClassForm.className"
            autocomplete="off"
            style="width: 40%"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddClass">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配课程表单 -->
    <el-dialog title="分配课程" :visible.sync="assginCoursedialogFormVisible">
      <el-form :model="assignCourseForm">
        <el-form-item label="选择学期" :label-width="formLabelWidth">
          <el-select
            v-model="assignCourseForm.semesterId"
            placeholder="请选择学期"
            @change="semesterChange"
          >
            <el-option
              v-for="semester in semesterList"
              :key="semester.id"
              :label="
                semester.term === 1
                  ? `${semester.year}年第一学期`
                  : `${semester.year}年第二学期`
              "
              :value="semester.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择课程" :label-width="formLabelWidth">
          <el-checkbox-group
            v-model="assignCourseForm.courseIdList"
            @change="courseIdChange"
          >
            <el-checkbox
              v-for="course in courseList"
              :key="course.id"
              :label="course.id"
              :disabled="course.selected"
            >
              {{ course.courseName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assginCoursedialogFormVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="addCourse">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getClassDetail,
  deleteClassById,
  addClass,
  updateClass,
} from "@/api/class";
import { getMajorByDeptId } from "@/api/major";
import { getAllGrade } from "@/api/grade";
import { getAllSemester } from "@/api/semester";
import { getUnAssignCourseList, assignCourse } from "@/api/course";
import { mapState } from "vuex";
export default {
  name: "ClassManage",
  data() {
    return {
      queryParams: {
        deptId: "",
        majorId: "",
        gradeId: "",
        className: "",
        pageNo: 1,
        pageSize: 5,
      },

      total: 0, // 总条数
      classData: [],
      majorList: [],
      gradeList: [],

      addDialogFormVisible: false,
      addClassForm: {
        classId: "",
        className: "",
        deptId: "",
        majorId: "",
        gradeId: "",
      },
      formLabelWidth: "120px",

      addDeptList: [],
      addClassData: [],
      addMajorList: [],
      addGradeList: [],

      addFormRules: {
        deptId: [{ required: true, message: "请选择院系", trigger: "change" }],
        majorId: [{ required: true, message: "请选择专业", trigger: "change" }],
        gradeId: [{ required: true, message: "请选择年级", trigger: "change" }],
        className: [
          { required: true, message: "请输入班级名", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "班级名长度应为 2~20 字符",
            trigger: "blur",
          },
        ],
      },

      isEditMode: false, //编辑模式标识

      assginCoursedialogFormVisible: false,

      assignCourseForm: {
        deptId: "", // 系
        classId: "", // 班级
        semesterId: "", // 学期
        courseIdList: [],
      },
      semesterList: [],
      courseList: [],
      originCourseList: [],
    };
  },

  computed: {
    ...mapState("dept", ["departments"]),
  },

  mounted() {
    this.getAllClassInfoByPage(this.queryParams);
    this.getAllDeptInfo();
  },

  methods: {
    // 获取所有系的id和name
    getAllDeptInfo() {
      this.$store.dispatch("dept/getAllDept");
    },
    // 添加课程 classId，semesterId, courseId
    async addCourse() {
      const diff = this.assignCourseForm.courseIdList.filter(
        (item) => !this.originCourseList.includes(item)
      );
      // 没有选择新课程点击添加
      if (diff.length == 0) {
        return;
      }

      // 添加新课程
      this.assignCourseForm.courseIds = diff;

      try {
        let res = await assignCourse(this.assignCourseForm);
        if (res.code == 200) {
          this.$message.success(res.data);
          this.assginCoursedialogFormVisible = false;
        } else {
          this.$message.error(res.msg);
        }
      } catch (error) {}
    },

    // 课程随学期更新
    async semesterChange(semesterId) {
      this.assignCourseForm.semesterId = semesterId;

      // 调接口获取课程数据
      try {
        let courseRes = await getUnAssignCourseList(this.assignCourseForm);
        this.courseList = courseRes.data;

        const ids = [];
        this.courseList.forEach((course) => {
          if (course.selected) {
            ids.push(course.id);
          }
        });
        this.assignCourseForm.courseIdList = ids;
        this.originCourseList = ids;
      } catch (error) {
        console.error("获取课程失败：", error);
      }
    },

    // 课程id发生变化
    courseIdChange() {},

    //为班级分配课程
    async assignCourseBtn(row) {
      this.courseList = [];
      this.originCourseList = [];

      this.assginCoursedialogFormVisible = true;
      try {
        // 发送请求获取学期数据
        let res = await getAllSemester();
        this.semesterList = res.data || [];
        let { id } = this.getCurrentTerm(this.semesterList);
        this.assignCourseForm.semesterId = id;
        // 发送请求获取未选择的课程数据
        //构建请求信息
        this.assignCourseForm.deptId = row.deptId;
        this.assignCourseForm.classId = row.classId;
        let courseRes = await getUnAssignCourseList(this.assignCourseForm);
        this.courseList = courseRes.data;

        const ids = new Array();
        this.courseList.forEach((course) => {
          if (course.selected) {
            ids.push(course.id);
          }
        });
        this.assignCourseForm.courseIdList = ids;
        this.originCourseList = ids;
      } catch (error) {}
    },

    //分页获取信息
    async getAllClassInfoByPage(params) {
      const queryParams = {
        ...params,
        deptId: params.deptId !== "" ? Number(params.deptId) : null,
        majorId: params.majorId !== "" ? Number(params.majorId) : null,
        gradeId: params.gradeId !== "" ? Number(params.gradeId) : null,
      };
      try {
        let res = await getClassDetail(queryParams);
        this.classData = res.data.records || [];
        this.total = res.data.total;
      } catch (e) {}
    },

    // 获取所有系的id和name
    // getAllDeptInfo() {
    //   if (this.departments.length == 0) {
    //     this.$store.dispatch("dept/getAllDept");
    //   }
    // },

    // 尺寸发生改变
    handleSizeChange(newVal) {
      this.queryParams.pageSize = newVal;
      //发送请求
      this.getAllClassInfoByPage(this.queryParams);
    },
    // 当前页发生改变
    handleCurrentChange(newVal) {
      this.queryParams.pageNo = newVal;
      //发送请求
      this.getAllClassInfoByPage(this.queryParams);
    },

    // 当院系发生改变
    async departmentChange(deptId) {
      // 先清空
      this.queryParams.majorId = "";
      this.queryParams.gradeId = "";
      this.majorList = [];
      this.gradeList = [];
      this.queryParams.pageNo = 1;

      this.getAllClassInfoByPage(this.queryParams);

      // 调用接口获取专业信息
      if (!deptId) {
        return;
      }
      try {
        let res = await getMajorByDeptId(deptId);
        this.majorList = res.data || [];
      } catch (error) {}
    },

    // 专业发生改变
    async majorChange() {
      // 清空
      this.queryParams.gradeId = "";
      this.gradeList = [];
      this.queryParams.pageNo = 1;

      this.getAllClassInfoByPage(this.queryParams);

      try {
        // 查询出年级
        let res = await getAllGrade();
        this.gradeList = res.data || [];
      } catch (e) {}
    },

    //选择年级发生改变
    gradeChange() {
      this.queryParams.pageNo = 1;
      this.getAllClassInfoByPage(this.queryParams);
    },

    //点击查询按钮
    queryClass() {
      this.getAllClassInfoByPage(this.queryParams);
    },

    // 删除按钮
    async deleteClass(row) {
      const { classId } = row;
      try {
        await this.$confirm("此操作将永久删除该班级，是否继续？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        // 用户点击"确定"后执行删除逻辑
        const res = await deleteClassById(classId);
        if (res.code === 200) {
          this.$message.success(res.data);
        } else {
          this.$message.error(res.msg);
        }
      } catch (error) {}
    },

    // 添加班级
    addClass() {
      this.addDialogFormVisible = true;
      this.isEditMode = false;
      console.log("departments", this.departments);
      this.addDeptList = this.departments;
      this.addClassForm = {
        classId: "",
        className: "",
        deptId: "",
        majorId: "",
        gradeId: "",
      };
    },

    // 添加部门发生改变
    async addDepartmentChange(deptId) {
      // 先清空
      this.addClassForm.majorId = "";
      this.addClassForm.gradeId = "";
      this.addMajorList = [];
      this.addGradeList = [];
      // 调用接口获取专业信息
      if (!deptId) {
        return;
      }
      try {
        let res = await getMajorByDeptId(deptId);
        this.addMajorList = res.data || [];
      } catch (error) {}
    },

    // 添加专业发生改变
    async addMajorChange() {
      // 清空
      this.addClassForm.gradeId = "";
      this.addGradeList = [];
      try {
        // 查询出年级
        let res = await getAllGrade();
        this.addGradeList = res.data || [];
      } catch (e) {}
    },

    // 点击提交 || 修改按钮
    submitAddClass() {
      this.$refs.addClassForm.validate(async (valid) => {
        if (valid) {
          const addParams = {
            ...this.addClassForm,
            deptId:
              this.addClassForm.deptId !== ""
                ? Number(this.addClassForm.deptId)
                : null,
            majorId:
              this.addClassForm.majorId !== ""
                ? Number(this.addClassForm.majorId)
                : null,
            gradeId:
              this.addClassForm.gradeId !== ""
                ? Number(this.addClassForm.gradeId)
                : null,
          };
          try {
            // 添加
            if (!this.isEditMode) {
              let res = await addClass(addParams);
              if (res.code == 200) {
                this.$message.success(res.data);
                this.addDialogFormVisible = false;
              } else {
                this.$message.error(res.msg);
              }
            }
            // 修改
            if (this.isEditMode) {
              let res = await updateClass(addParams);
              if (res.code == 200) {
                this.$message.success(res.data);
                this.addDialogFormVisible = false;
                this.isEditMode = false;
              } else {
                this.$message.error(res.msg);
              }
            }
            this.getAllClassInfoByPage(this.queryParams);
          } catch (error) {}
        } else {
          return false;
        }
      });
    },

    //点击修改按钮
    async updateClass(row) {
      this.addDialogFormVisible = true;
      this.isEditMode = true;
      this.addClassForm = {
        ...row,
      };

      this.addClassForm = {
        ...row,
      };
      // 加载关联数据
      try {
        // 加载专业列表
        const majorRes = await getMajorByDeptId(row.deptId);
        this.addMajorList = majorRes.data || [];
        // 加载年级列表
        const gradeRes = await getAllGrade();
        this.addGradeList = gradeRes.data || [];
      } catch (error) {
        console.error("加载数据失败:", error);
      }
    },

    getCurrentTerm(semesters, currentDateStr) {
      const currentDate = new Date(currentDateStr || new Date());

      // 转换日期为 Date 对象，并排序（按 startDate）
      const sortedSemesters = semesters
        .map((s) => ({
          ...s,
          startDateObj: new Date(s.startDate),
          endDateObj: new Date(s.endDate),
        }))
        .sort((a, b) => a.startDateObj - b.startDateObj);

      // 先尝试匹配当前在哪个学期
      for (let sem of sortedSemesters) {
        if (currentDate >= sem.startDateObj && currentDate <= sem.endDateObj) {
          return sem; // 当前日期在该学期范围内
        }
      }

      // 如果当前日期不在任何学期范围内，则选"当前日期之前"的最后一个学期
      let previousSemester = null;
      for (let sem of sortedSemesters) {
        if (currentDate >= sem.endDateObj) {
          previousSemester = sem;
        } else {
          break;
        }
      }

      return previousSemester; // 可能为 null（当前在所有学期之前）
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  margin: 20px;

  .header {
    display: flex;
    flex-wrap: wrap;
    gap: 16px; // 控制各项间距
    align-items: center;
  }

  .form-item {
    display: flex;
    align-items: center;
    min-width: 200px;
    flex: 1; // 让所有form-item平均分配空间
    white-space: nowrap;

    span {
      margin-right: 8px;
      font-weight: 500;
      white-space: nowrap;
    }

    .el-input,
    .el-select {
      flex: 1;
      min-width: 120px;
    }
  }

  .content {
    margin-top: 30px;
    .el-pagination {
      margin-top: 30px;
      display: flex;
      justify-content: center; // ✅ 水平居中
    }
  }
}
</style>